package com.csp.base.jobconfig.config;

import java.io.IOException;
import java.util.Properties;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.ee.servlet.QuartzInitializerListener;
import org.quartz.impl.matchers.EverythingMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import com.csp.base.jobconfig.factory.JobFactory;
import com.csp.base.jobconfig.listener.SimpleJobListener;

@Configuration
public class SchedulerConfig {
	@Autowired
	JobFactory jobFactory;
	@Bean(name = "SchedulerFactory")
	public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
		SchedulerFactoryBean factory = new SchedulerFactoryBean();
		factory.setJobFactory(jobFactory);
		factory.setQuartzProperties(quartzProperties());
		return factory;
	}

	@Bean
	public Properties quartzProperties() throws IOException {
		PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
		propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
		propertiesFactoryBean.afterPropertiesSet();
		return propertiesFactoryBean.getObject();
	}

	@Bean
	public QuartzInitializerListener executorListener() {
		return new QuartzInitializerListener();
	}

	@Bean(name = "Scheduler")
	public Scheduler scheduler() throws IOException, SchedulerException {
		Scheduler scheduler = schedulerFactoryBean().getScheduler();
		scheduler.getListenerManager().addJobListener(new SimpleJobListener(), EverythingMatcher.allJobs());
		return scheduler;
	}
}